package com.jiazhong.example.project.shoppingcart.service.impl;

import com.jiazhong.example.project.shoppingcart.bean.Carts;
import com.jiazhong.example.project.shoppingcart.bean.Users;
import com.jiazhong.example.project.shoppingcart.mapper.CartsMapper;
import com.jiazhong.example.project.shoppingcart.mapper.StockMapper;
import com.jiazhong.example.project.shoppingcart.service.CartsService;
import com.jiazhong.example.project.shoppingcart.util.JsonResult;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class CartsServiceImpl implements CartsService {
    private CartsMapper cartsMapper;
    private StockMapper stockMapper;
    ;
    private SqlSession session;
    private SqlSessionFactory ssf;

    public CartsServiceImpl() {
        InputStream inputStream = UsersServiceImpl.class.getClassLoader().getResourceAsStream("config.xml");
        ssf = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Override
    public JsonResult saveOrUpdate(Carts carts) {
        session = ssf.openSession();
        cartsMapper = session.getMapper(CartsMapper.class);
        // 先更新
        int row;
        try {
            row = cartsMapper.update(carts);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(500, "加入购物车失败");
        }
        if (row == 0) {
            // 在添加
            try {
                row = cartsMapper.save(carts);
            } catch (Exception e) {
                e.printStackTrace();
                return new JsonResult(500, "加入购物车失败");
            }
            if (row == 0) {
                return new JsonResult(500, "加入购物车失败");
            }
        }

        stockMapper = session.getMapper(StockMapper.class);
        try {
            stockMapper.updateNumber1(carts.getBookId());
        } catch (Exception e) {
            session.rollback();
            return new JsonResult(500, "加入购物车失败");
        }
        session.commit();
        return new JsonResult("加入购物车成功");
    }

    @Override
    public JsonResult findByUserId(Integer userId) {
        session = ssf.openSession();
        cartsMapper = session.getMapper(CartsMapper.class);
        List<Carts> carts = cartsMapper.findByUserId(userId);
        return new JsonResult(carts);
    }

    @Override
    public JsonResult deleteById(int id) {
        session = ssf.openSession();
        cartsMapper = session.getMapper(CartsMapper.class);
        int row;
        // 1.获取到id对应的购物车信息
        Carts carts = cartsMapper.findById(id);
        // 2.删除该id的购物车信息
        row = cartsMapper.deleteById(id);
        if (row == 0) {
            return new JsonResult(500, "删除购物车制定内容失败");
        }
        // 3.增加对应图书的库存
        StockMapper stockMapper = session.getMapper(StockMapper.class);
        row = stockMapper.updateNumber3(carts.getBookId(), 0 - carts.getNumber());
        if (row == 0) {
            return new JsonResult(500, "删除购物车制定内容失败");
        }
        session.commit();
        return new JsonResult("success");
    }

    @Override
    public JsonResult deleteByBatch(String val) {
        session = ssf.openSession();
        cartsMapper = session.getMapper(CartsMapper.class);
        String[] ids = val.split(",");
        List<String> list = Arrays.asList(ids);
        // 1.查询要删除的购物车信息
        List<Carts> carts = cartsMapper.findByIds(list);
        // 2.删除选中的购物车信息
        int row = cartsMapper.deleteByBatch(list);
        if (row == 0) {
            return new JsonResult(500, "批量删除失败");
        }
        // 3.更新选中删除的库存信息
        StockMapper stockMapper = session.getMapper(StockMapper.class);
        boolean flag = true;
        for (int i = 0; i < carts.size(); i++) {
            Carts c = carts.get(i);
            row = stockMapper.updateNumber3(c.getBookId(), 0 - c.getNumber());
            if (row == 0) {
                flag = false;
                break;
            }
        }
        if (flag) {
            session.commit();
        } else {
            session.rollback();
            return new JsonResult(500, "批量删除失败");
        }
        return new JsonResult("success");
    }

    @Override
    public JsonResult changeCartNumber(int userId, int bookId, int number) {
        session = ssf.openSession();
        cartsMapper = session.getMapper(CartsMapper.class);
        Carts carts = new Carts();
        carts.setUserId(userId);
        carts.setBookId(bookId);
        int row;
        // 更新购物车中的数量
        if (number == 1) {
            row = cartsMapper.update(carts);
        } else if (number == -1) {
            row = cartsMapper.update1(carts);
        } else {
            carts.setQuantity(number);
            row = cartsMapper.update2(carts);
        }
        if (row == 0) {
            return new JsonResult(500, "更新购物车失败");
        }
        // 更新库存的数量
        stockMapper = session.getMapper(StockMapper.class);
        try {
            if (number == 1) {
                stockMapper.updateNumber1(carts.getBookId());
            } else if (number == -1) {
                stockMapper.updateNumber2(carts.getBookId());
            } else {
                stockMapper.updateNumber3(bookId, number);
            }
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
            return new JsonResult(500, "更新购物车失败");
        }
        session.commit();
        return new JsonResult("success");
    }

    @Override
    public JsonResult deleteAll(HttpSession session) {
        // 1.得到userId
        Users user = (Users) session.getAttribute("user");
        // 2.获取到该用户的所有购物车信息
        this.session = ssf.openSession();
        cartsMapper = this.session.getMapper(CartsMapper.class);
        List<Carts> carts = cartsMapper.findByUserId(user.getId());
        // 3.清空用户购物车
        AtomicInteger row = new AtomicInteger(cartsMapper.deleteByUserId(user.getId()));
        if (row.get() == 0) {
            this.session.rollback();
            return new JsonResult(500, "清空购物车失败");
        }
        // 4.恢复库存
        stockMapper = this.session.getMapper(StockMapper.class);
        AtomicBoolean flag = new AtomicBoolean(true);
        carts.forEach(e -> {
            row.set(stockMapper.updateNumber3(e.getBookId(), 0 - e.getNumber()));
            if (row.get() == 0) {
                flag.set(false);
            }
        });
        if (!flag.get()) {
            this.session.rollback();
            return new JsonResult(500, "清空购物车失败");
        }
        this.session.commit();
        return new JsonResult("success");
    }
}
